package com.sxm.yiwei.fragments;


import android.app.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;


import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.BuyCarActivity;
import com.sxm.yiwei.activitis.FWShopActivity;
import com.sxm.yiwei.activitis.HelpActivity;
import com.sxm.yiwei.activitis.HomeHopeStoreActivity;
import com.sxm.yiwei.activitis.HomeMakeMoneyActivity;
import com.sxm.yiwei.activitis.HomeSearchActivity;
import com.sxm.yiwei.activitis.HopeActivity;

import com.sxm.yiwei.activitis.HotSendActivity;
import com.sxm.yiwei.activitis.MineNotification;
import com.sxm.yiwei.activitis.OnceSendActivity;
import com.sxm.yiwei.activitis.UserLoginActivity;
import com.sxm.yiwei.activitis.UserUpActivity;
import com.sxm.yiwei.adapters.HomeListAdapter;
import com.sxm.yiwei.beans.ShopList;

import com.sxm.yiwei.pinche.PincheActivity;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.MyListview;
import com.sxm.yiwei.views.PullToRefreshView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 *
 * 首页页面
 * A simple {@link Fragment} subclass.
 *
 */


public class HomeFragment extends BaseFragment implements View.OnClickListener, AMapLocationListener, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener {
    private LinearLayout imgbt1,imgbt2,imgbt3,imgbt4,imgbt5,imgbt6;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private View view;
    private MyListview homelistview;
    private List<ShopList.DataBean> homelist = new ArrayList<>();
    private List<ShopList.DataBean.ServiceListBean> homegridlist;

    private RelativeLayout searchbt;
    private ImageView gouwuche;
    private ImageView zhuanqian;
    private TextView cityText;
    private ScrollView homeScroll;
    private String longitude;
    private String latitude;
    private String appId ;
    private AlertDialog dialog;
    private int page = 1;// 页码
    private int itemNo = 15;// 每页请求的条目

    private HomeListAdapter homeListAdapter;
    private ImageView jiazheng;
    private ImageView paotui;
    private ImageView baoyang;
    private ImageView qiche;
    private ImageView xianshang;
    private ImageView peiwan;
    private ImageView anmo;
    private ImageView shenghuo;
    private ImageView qita;
    private ImageView laowu;
    private double latitude1;
    private double longitude1;
    private String city;
    private PullToRefreshView root;
    private JSONArray data;
    private ImageView nodata;
    private AlertDialog.Builder builder;
    private TextView homehow;
    private TextView homecitor;
    private RelativeLayout hopeStore;
    private String city1;
    private int afterPage;

    @Override
    public void onStart() {
        super.onStart();
        sharedPreferences = getActivity().getApplicationContext().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        city = sharedPreferences.getString("city", "杭州");
        cityText.setText(city);
    }

    public HomeFragment() {
        // Required empty public constructor
    }
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            dialog.dismiss();
        }
    };


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            return;
        }else {

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        sharedPreferences = getActivity().getApplicationContext().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        city = sharedPreferences.getString("city", "杭州");
        getLoc();
        // 初始化控件
        initview(view);

        if (true){
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.NoBackGroundDialog);
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.progress_dialog, null);
            builder.setView(view);
            dialog = builder.create();
            dialog.setCancelable(false);
            dialog.show();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    getShopList(page,itemNo);
                }
            }).start();

       }else {}
        Timer timer = new Timer();
        timer.schedule(task,3000);
        // 将视图显示顶部
        return view;
    }

    // 获取店铺列表
    private void getShopList(final int page,int itemNo) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.HOMEGETSHOPLIST);
        params.addHeader("Content-Type","application/json");
        JSONObject object = new JSONObject();
        if (appId.equals("")){
            params.addHeader("appId", "337cb33f-83bd-11e7-9812-00163e0a3457");
            object.put("longitude","120.250");
            object.put("latitude","30.500");
        }else {
            params.addHeader("appId", appId);
            if (longitude.equals("")){
                object.put("longitude","120.88");
                object.put("latitude","30.88");
            }else {
                object.put("longitude",longitude);
                object.put("latitude",latitude);
            }
        }
        object.put("pageNo", page +"");
        object.put("pageSize",itemNo+"");
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                getShopData(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

        // 获取信息
    private void getShopData(String result) {
        JSONObject obj = JSON.parseObject(result);
        data = obj.getJSONArray("data");
      //  afterPage = obj.getString("afterPage");
        afterPage = Integer.valueOf(obj.getString("afterPage"));
        if (data.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
            String avatar = obj1.getString("avatar");
            String distance = obj1.getString("distance");
            String gradeCode = obj1.getString("gradeCode");
            String id = obj1.getString("id");
            String isInsurance = obj1.getString("isInsurance");
            String name = obj1.getString("name");
            String sellGrade = obj1.getString("sellGrade");
            String type = obj1.getString("type");
            String volume = obj1.getString("volume");
            String openStatus = obj1.getString("openStatus");
            ShopList.DataBean dataBean= new ShopList.DataBean();
            dataBean.setAvatar(avatar);
            dataBean.setDistance(Double.valueOf(distance));
            dataBean.setGradeCode(Integer.valueOf(gradeCode));
            if (isInsurance.equals("true")){
                dataBean.setIsInsurance(true);
            }else {
                dataBean.setIsInsurance(false);
            }
            if (openStatus.equals("true")){
                dataBean.setOpenStatus(true);
            }else {
                dataBean.setOpenStatus(false);
            }
            dataBean.setId(id);
            dataBean.setName(name);
            if (isInsurance.equals("true")){
                dataBean.setIsInsurance(true);
            }else {
                dataBean.setIsInsurance(false);
            }
            dataBean.setSellGrade(Integer.valueOf(sellGrade));
            dataBean.setType(Integer.valueOf(type));
            dataBean.setVolume(Integer.valueOf(volume));
            homegridlist = new ArrayList<>();
            JSONArray serviceList = obj1.getJSONArray("serviceList");
            if (serviceList!=null) {
                for (int j = 0; j < serviceList.size(); j++) {
                    JSONObject obj2 = JSON.parseObject(String.valueOf(serviceList.get(j)));
                    String amount = obj2.getString("amount");
                    String serviceid = obj2.getString("id");
                    String servicename = obj2.getString("name");
                    String serviceAvatar = obj2.getString("serviceAvatar");
                    String servicevolume = obj2.getString("volume");
                    String unit = obj2.getString("unit");
                    ShopList.DataBean.ServiceListBean serviceListBean = new ShopList.DataBean.ServiceListBean();
                    serviceListBean.setVolume(Integer.valueOf(servicevolume));
                    serviceListBean.setName(servicename);
                    serviceListBean.setAmount(Double.valueOf(amount));
                    serviceListBean.setId(serviceid);
                    serviceListBean.setServiceAvatar(serviceAvatar);
                    serviceListBean.setUnit(Integer.valueOf(unit));
                    homegridlist.add(serviceListBean);
                }
            }else {}
                dataBean.setServiceList(homegridlist);
                homelist.add(dataBean);
        }
        homeListAdapter = new HomeListAdapter(getActivity(),homelist);
        homelistview.setAdapter(homeListAdapter);
        homeListAdapter.notifyDataSetChanged();
        homeListAdapter.setHomeListOnClickListener(new HomeListAdapter.HomeListOnClickListener() {
            @Override
            public void homeListOnClickListener(int i) {
                ShopList.DataBean item = (ShopList.DataBean) homeListAdapter.getItem(i);
                final String itemId = item.getId();
                boolean openStatus = item.isOpenStatus();

                if (openStatus){
                    Intent intent = new Intent(getActivity(),FWShopActivity.class);
                    intent.putExtra("id",itemId);
                    startActivity(intent);
                }else {
                    builder =  new AlertDialog.Builder(getActivity());
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.amount_dialog, null);
                    builder.setView(view);
                    Button cancel = (Button) view.findViewById(R.id.amount_cancel);
                    Button sure = (Button) view.findViewById(R.id.amount_sure);
                    TextView message = (TextView) view.findViewById(R.id.amount_message);
                    TextView title = (TextView) view.findViewById(R.id.amount_title);
                    title.setText("温馨提示");
                    message.setText("店家暂时休息中可能无法为你服务哦");
                    cancel.setText("返回");
                    sure.setText("进店逛逛");
                    final AlertDialog dialog = builder.create();
                    cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(),FWShopActivity.class);
                            intent.putExtra("id",itemId);
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }


            }

        });


    }


    // 获取位置信息 经纬度
    public void getLoc() {
        AMapLocationClient client = new AMapLocationClient(getActivity());
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(300000);
        client.setLocationListener(this);
        client.setLocationOption(option);
        client.startLocation();
    }
    @Override
    public void onResume() {
        super.onResume();
    }


    // 初始化控件方法
    private void initview(View view) {
        homehow = (TextView) view.findViewById(R.id.home_how);
        homecitor = (TextView) view.findViewById(R.id.home_citor);
        hopeStore = (RelativeLayout) view.findViewById(R.id.home_hopestore);
        searchbt = (RelativeLayout) view.findViewById(R.id.home_searchbt);
        gouwuche = (ImageView) view.findViewById(R.id.home_gouwuche);
        zhuanqian = (ImageView) view.findViewById(R.id.home_zhuanqian);
        cityText = (TextView) view.findViewById(R.id.home_citytext);
        imgbt1 = (LinearLayout) view.findViewById(R.id.home_imgbt1);
        imgbt2 = (LinearLayout) view.findViewById(R.id.home_imgbt2);
        imgbt3 = (LinearLayout) view.findViewById(R.id.home_imgbt3);
        imgbt4 = (LinearLayout) view.findViewById(R.id.home_imgbt4);
        imgbt5 = (LinearLayout) view.findViewById(R.id.home_imgbt5);
        imgbt6 = (LinearLayout) view.findViewById(R.id.home_imgbt6);
        homelistview = (MyListview) view.findViewById(R.id.home_listview);
        nodata = (ImageView) view.findViewById(R.id.home_nodata);
        root = (PullToRefreshView) view.findViewById(R.id.refresh_root);
        root.setOnHeaderRefreshListener(this);
        root.setOnFooterRefreshListener(this);
        root.setLastUpdated(new Date().toLocaleString());
        homelistview.setFocusable(false);
        laowu = (ImageView) view.findViewById(R.id.home_laowu);
        jiazheng = (ImageView) view.findViewById(R.id.home_jiazheng);
        paotui = (ImageView) view.findViewById(R.id.home_paotui);
        baoyang = (ImageView) view.findViewById(R.id.home_baoyang);
        qiche = (ImageView) view.findViewById(R.id.home_qiche);
        xianshang = (ImageView) view.findViewById(R.id.home_xianshang);
        peiwan = (ImageView) view.findViewById(R.id.home_peiwan);
        anmo = (ImageView) view.findViewById(R.id.home_anmo);
        shenghuo = (ImageView) view.findViewById(R.id.home_shenghuo);
        qita = (ImageView) view.findViewById(R.id.home_qita);
        //设置搜索按钮 颜色变化 设置默认
        searchbt.setOnClickListener(this);
        gouwuche.setOnClickListener(this);
        zhuanqian.setOnClickListener(this);
        hopeStore.setOnClickListener(this);
        // 设置点击事件
        imgbt1.setOnClickListener(this);
        imgbt2.setOnClickListener(this);
        imgbt3.setOnClickListener(this);
        imgbt4.setOnClickListener(this);
        imgbt5.setOnClickListener(this);
        imgbt6.setOnClickListener(this);
        laowu.setOnClickListener(this);
        jiazheng.setOnClickListener(this);
        paotui.setOnClickListener(this);
        baoyang.setOnClickListener(this);
        qiche.setOnClickListener(this);
        xianshang.setOnClickListener(this);
        peiwan.setOnClickListener(this);
        anmo.setOnClickListener(this);
        shenghuo.setOnClickListener(this);
        qita.setOnClickListener(this);
        homehow.setOnClickListener(this);
        homecitor.setOnClickListener(this);

        homeScroll = (ScrollView) view.findViewById(R.id.home_scroll);
        homeScroll.smoothScrollTo(0,0);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }

    // 点击事件方fa
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home_hopestore:
                startActivity(new Intent(getActivity(), HomeHopeStoreActivity.class));
                break;
            case R.id.home_citor:// 城市合伙人
                startActivity(new Intent(getActivity(), MineNotification.class));
                break;
            case R.id.home_how://如何赚钱
                startActivity(new Intent(getActivity(), HomeMakeMoneyActivity.class));
                break;
            case R.id.home_laowu:
                Intent i = new Intent(getActivity(),HomeSearchActivity.class);
                i.putExtra("t","劳务市场");
                startActivity(i);
                break;
            case R.id.home_peiwan:
                Intent i1 = new Intent(getActivity(),HomeSearchActivity.class);
                i1.putExtra("t","陪玩导游");
                startActivity(i1);
                break;
            case R.id.home_jiazheng:
                Intent i2 = new Intent(getActivity(),HomeSearchActivity.class);
                i2.putExtra("t","家政服务");
                startActivity(i2);
                break;
            case R.id.home_paotui:
                Intent i3 = new Intent(getActivity(),HomeSearchActivity.class);
                i3.putExtra("t","跑腿办事");

                startActivity(i3);
                break;
            case R.id.home_baoyang:
                Intent i4 = new Intent(getActivity(),HomeSearchActivity.class);
                i4.putExtra("t","维修保养");

                startActivity(i4);
                break;
            case R.id.home_qiche:
                Intent i5 = new Intent(getActivity(),HomeSearchActivity.class);
                i5.putExtra("t","汽车服务");

                startActivity(i5);
                break;
            case R.id.home_xianshang:
                Intent i6 = new Intent(getActivity(),HomeSearchActivity.class);
                i6.putExtra("t","线上服务");
                startActivity(i6);
                break;
            case R.id.home_shenghuo:
                Intent i7 = new Intent(getActivity(),HomeSearchActivity.class);
                i7.putExtra("t","生活服务");
                startActivity(i7);
                break;
            case R.id.home_qita:
                Intent i8 = new Intent(getActivity(),HomeSearchActivity.class);
                i8.putExtra("t","其他");
                startActivity(i8);
                break;
            case R.id.home_anmo:
                Intent i9 = new Intent(getActivity(),HomeSearchActivity.class);
                i9.putExtra("t","按摩美容");
                startActivity(i9);
                break;
            case R.id.home_searchbt:

                startActivity(new Intent(getActivity(), HomeSearchActivity.class));
                break;
            case R.id.home_gouwuche:

                startActivity(new Intent(getActivity(),BuyCarActivity.class));
                break;
            case R.id.home_zhuanqian:
                // startActivity(new Intent(getActivity(),UserUpActivity.class));
               buidleToast();
                break;
            case R.id.home_imgbt1:
                    startActivity(new Intent(getActivity(), HotSendActivity.class));
                break;
            case R.id.home_imgbt2:
                Toast.makeText(getActivity(), "一键发单", Toast.LENGTH_SHORT).show();
               // startActivity(new Intent(getActivity(), OnceSendActivity.class));
                if (token==""){

                    startActivity(new Intent(getActivity(), UserUpActivity.class));


                }else{
                    //  buidleToast();
                    startActivity(new Intent(getActivity(), OnceSendActivity.class));
                }

                break;
            case R.id.home_imgbt3:

                    startActivity(new Intent(getActivity(), HelpActivity.class));
                break;
            case R.id.home_imgbt4://拼车
                token = sharedPreferences.getString("token", "");
                if (token.equals("")){
                    startActivity(new Intent(getActivity(), UserUpActivity.class));
                }else{
                    startActivity(new Intent(getActivity(), PincheActivity.class));
                }
                //startActivity(new Intent(getActivity(), PincheActivity.class));
                break;
            case R.id.home_imgbt5://拼车
                if (token==""){

                    startActivity(new Intent(getActivity(), UserUpActivity.class));

                }else{
                    // buidleToast();
                    startActivity(new Intent(getActivity(), HopeActivity.class));
                }

                break;
            case R.id.home_imgbt6://拼车
                Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
                break;
        }
    }
    public void buidleToast(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View diaview = LayoutInflater.from(getActivity()).inflate(R.layout.buidletoast_dia, null);
        builder.setView(diaview);
        View surebt = diaview.findViewById(R.id.buidle_diabt);
        final AlertDialog dialog = builder.create();
        surebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        latitude1 = aMapLocation.getLatitude();
        longitude1 = aMapLocation.getLongitude();
        city1 = aMapLocation.getCity();
        cityText.setText(city1);
        String rid = sharedPreferences.getString("rid", "");
        SharedPreferences.Editor edit = sharedPreferences.edit();
        if (city1==null){
            edit.putString("city","杭州");
        }else {
            edit.putString("city",city1);
        }

        edit.commit();
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        root.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (afterPage==itemNo){
                    page++;
                    getShopList(page,itemNo);
                    homeListAdapter.notifyDataSetChanged();
                }else if (afterPage<itemNo){
                    homelist.clear();
                    itemNo=page*itemNo;
                    page=1;
                    getShopList(page,itemNo);
                    if (homeListAdapter!=null){
                        homeListAdapter.notifyDataSetChanged();
                    }

                }
                root.onHeaderRefreshComplete();
            }
        },2000);
    }
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        root.postDelayed(new Runnable() {
            @Override
            public void run() {
                   if (afterPage==itemNo){
                       page++;
                       getShopList(page,itemNo);
                       homeListAdapter.notifyDataSetChanged();
                   }else if (afterPage<itemNo){
                       homelist.clear();
                       itemNo=page*itemNo;
                       page=1;
                       getShopList(page,itemNo);
                       if (homeListAdapter!=null){
                           homeListAdapter.notifyDataSetChanged();
                       }
                   }

                root.onFooterRefreshComplete();
            }
        },2000);
    }
}
